# This script requires the following Python libraries:
# - pygments: Used for syntax highlighting of code.
# - chardet: Used for detecting the encoding of files.
# You can install these libraries using pip:
# pip install pygments chardet

import os
from pygments import highlight
from pygments.lexers import CppLexer
from pygments.formatters import TerminalFormatter
from pygments.formatters import Terminal256Formatter
import chardet
import time

def highlight_and_print_file(file_path, rate=500):
    """读取文件，应用高亮，并以特定速率打印到控制台"""
    with open(file_path, 'rb') as file:  # 以二进制模式打开文件
        raw_data = file.read()
    encoding = chardet.detect(raw_data)['encoding']  # 检测编码

    # 使用检测到的编码解码文件内容
    code = raw_data.decode(encoding)
    
    highlighted_code = highlight(code, CppLexer(), Terminal256Formatter())
    start_time = time.time()  # 记录开始打印的时间
    for char in highlighted_code:
        print(char, end='', flush=True)
        time.sleep(1 / rate)
    
    elapsed_time = time.time() - start_time  # 计算打印用时
    if elapsed_time < 1:
        time.sleep(1 - elapsed_time)  # 如果打印时间少于一秒，则等待剩余时间

def collect_files(folder_path):
    """收集文件夹下的所有.h和.cpp文件的路径"""
    file_paths = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.h') or file.endswith('.cpp'):
                file_path = os.path.join(root, file)
                file_paths.append(file_path)
    return file_paths

def process_files_in_order(folder_path, order):
    """按照给定的顺序处理文件"""
    file_paths = collect_files(folder_path)
    sorted_files = sorted(file_paths, key=lambda x: order.index(x) if x in order else len(order))
    
    for file_path in sorted_files:
        os.system('cls' if os.name == 'nt' else 'clear')  # 根据操作系统清空控制台
        print(f"\n\nProcessing file: {file_path}\n")
        highlight_and_print_file(file_path)

# 设置你的文件夹路径
folder_path = 'D:\\图灵院\\learnopengl\\src'
# 用户定义的文件处理顺序
order = [
    'D:\\图灵院\\learnopengl\\src\\DebugManager.cpp',
    'D:\\图灵院\\learnopengl\\src\\DebugManager.h',
    'D:\\图灵院\\learnopengl\\src\\BoundingBox.cpp',
    'D:\\图灵院\\learnopengl\\src\\BoundingBox.h',
    'D:\\图灵院\\learnopengl\\src\\Ray.cpp',
    'D:\\图灵院\\learnopengl\\src\\Ray.h',
    'D:\\图灵院\\learnopengl\\src\\Model.cpp',
    'D:\\图灵院\\learnopengl\\src\\Model.h',
    'D:\\图灵院\\learnopengl\\src\\Mesh.cpp',
    'D:\\图灵院\\learnopengl\\src\\Mesh.h',
    'D:\\图灵院\\learnopengl\\src\\node.cpp',
    'D:\\图灵院\\learnopengl\\src\\node.h',
    'D:\\图灵院\\learnopengl\\src\\Camera.cpp',
    'D:\\图灵院\\learnopengl\\src\\Camera.h',
    'D:\\图灵院\\learnopengl\\src\\Application.cpp',
    'D:\\图灵院\\learnopengl\\src\\Application.h',
    'D:\\图灵院\\learnopengl\\src\\Shader.cpp',
    'D:\\图灵院\\learnopengl\\src\\Shader.h',
    'D:\\图灵院\\learnopengl\\src\\main.cpp',
]
# 输出collect_files函数收集到的所有文件路径
all_files = collect_files(folder_path)
#for file in all_files:
    #print(f"'{file}',")

process_files_in_order(folder_path, order)